<template>
	<Page class="apply-form">
		<div class="questiion_head">
			<div class="head_title"><img src="~img/cydnQt/title.png" /></div>
			<div class="head_sub_tip">企业信息收集</div>
			<div class="bg_box">
				<div class="flex">
					<div class="short">{{ info.shortName || '' }}</div>
					<div class="content">
						<div class="name">{{ info.corpName }}</div>
						<div class="code">统一信用代码：{{ info.corpCredit }}</div>
					</div>
				</div>
			</div>
		</div>
		<div class="content_box">
			<div class="question">
				<!-- 问卷内容 -->
				<div v-for="item in form.titleItems" :key="item.id">
					<div v-for="(items, index) in item.questionItems" :key="index">
						<!-- 标题处理 -->
						<div v-if="index == 0" class="title-qt">一、合规持续经营</div>
						<div v-if="index == 6" class="title-qt">二、客户有固定经营场所</div>
						<div v-if="index == 10" class="title-qt">三、客户经营状况良好</div>
						<div v-if="index == 15" class="title-qt">四、客户有真实的融资需求</div>
						<questionOne
							:qType="items.questionType"
							:question="items"
							:answer="answer.answerItems[items.itemOrder - 1]"
							:index="index"
						></questionOne>
					</div>
				</div>
				<div>
					<van-checkbox icon-size="16px" shape="square" v-model="confirmR" :disabled="canClick">
						<div style="color: #000; height:18px; display: flex; align-items: center;">该公司已阅读确认相关法律风险提示</div>
					</van-checkbox>
					<div class="tips">
						法律风险提示内容：本人承诺获取的贷款资金真实用于生产经营，不挪用于房地产、债券、期货、金融衍生产品和资产管理产品等投资、固定资产和股本权益性投资、民间借贷以及国家有关法律法规和规章等规定的禁止信贷资金流入的其他领域。
					</div>
				</div>
				<div class="sign-hand" v-if="confirmR" id="sign_hand" @click="goToSign('qianqiwanhu')">
					<div v-if="!qianqiwanhuImgSrc && !signPic">点击进行签字</div>
					<img style="max-height: 260px" v-if="qianqiwanhuImgSrc || signPic" :src="qianqiwanhuImgSrc || signPic" alt="" />
				</div>
				<div class="submit-btn" v-if="showBtn">
					<van-button class="submit-bo" :loading="loading" @click="goSub">保存</van-button>
				</div>
			</div>
		</div>
	</Page>
</template>

<script>
	import {
		paperList,
		token_cydn,
		getVisitDetail,
		questionsSee,
		questionsAnswer,
		answerSubmit,
		updateVisitDetail,
	} from '@/interfaces/cydnQt';
	import { cosUpload } from '@/interfaces/mini';
	import questionOne from './components/questionOne.vue';
	import { Dialog } from 'vant';

	export default {
		name: 'qtA',
		components: { questionOne },
		data() {
			return {
				dataList: {},
				form: {},
				answer: {
					answerId: '',
					questionId: null,
					doTime: 0,
					answerItems: [],
				},
				answer1: '',
				info: {
					shortName: '',
					signPic: '',
				},
				isWrite: true,
				loading: false,
				confirmR: false,
				// 签名对象
				qianqiwanhuSigner: {
					context_id: 20, // id
					custName: 'qianqiwanhu', // 签名人姓名
					identificationNumber: '11111*****XXXX', // 签名人身份证
					keyword: '签名', // 签名关键字，按照这个去对pdf
					hint: '请在下方进行签字确认', // 提示信息(支持html)
				},
				qianqiwanhuImgSrc: null, // 签名图片
				surveyId: '2e4009d56f304207bea5fd255e09f19f', // 问卷模板id
				signPic: '',
				canClick: false,
        showBtn: false
			};
		},
		created() {
			// 监听签名事件
			this.$eventBus.$on(
				'signed',
				(data) => {
					if (data.context_id === 20) {
						this.qianqiwanhuImgSrc = data.imgSrc;
						// console.log(this.qianqiwanhuImgSrc, 'this.qianqiwanhuImgSrc');
						// 滚动置底
						setTimeout(() => {
							this.toBottom();
						}, 200);
					}
				},
				this
			);
			this.tokenCydn();
		},
		methods: {
			toBottom() {
				const jyDom = document.querySelector('#sign_hand');
				console.log(jyDom, 'jyDom');
				jyDom.scrollIntoView({
					behavior: 'smooth',
					block: 'start',
					inline: 'nearest',
				});
			},
			async tokenCydn() {
				let param = {
					username: this.getUrlParam('phone'),
					platform: 'miniApp',
				};
				const res = await token_cydn(param);
				console.log(res, '登录');
				if (res.code == 200) {
					// 更新state中的token_cydn
					this.$store.commit('user/setState', {
						attr: 'token_cydn',
						data: res.token,
					});
					this.getIds();
				}
			},
			async getIds() {
				const params = {
					//id:'9777711e-8949-42bc-a09a-eedc8a12bb50' //url带上的
					id: this.getUrlParam('id') || '',
				};
				const res = await getVisitDetail(params);
				console.log(res, 'getVisitDetail');
				if (res.code == 200) {
					this.info = res.data;
					this.signPic = this.info.signPic || '';
					this.confirmR = this.signPic ? true : false;
					this.canClick = this.signPic ? true : false;
          this.showBtn = this.info.saveStatus == '1' ? false : true;
					this.getIsWrite();
				}
			},
			async getIsWrite() {
				// 需要反显
				if (this.info.answerId) {
					this.isWrite = true;
					this.getAnswer(this.info.answerId);
				} else {
					this.isWrite = false;
					this.getDetails();
				}
			},
			async getDetails(type) {
				const params = {
					id: this.info.surveyId || this.surveyId,
				};
				const res = await paperList(params);
				if (res.code == 200) {
					if (type) {
						this.dataList = {
							...this.dataList,
							id: res.data.id,
						};
					} else {
						this.dataList = res.data;
						this.getTemplate();
					}
				}
			},
			async getAnswer(id) {
				const res = await questionsAnswer({ id: id });
				if (res.code == 200) {
					this.answer1 = res.data.answer;

					this.getDetails();
				}
			},
			getTemplate() {
				let answer = this.answer1;
				this.dataList.titleItems[0].questionItems.forEach((ele, index) => {
					if (this.isWrite) {
						const cpList = JSON.parse(JSON.stringify(this.answer1.answerItems));
						const findOne = cpList.find((pre) => pre.questionId === ele.id);
						if (findOne) {
							findOne.contentArray = findOne.contentArray ? findOne.contentArray : [];
							findOne.itemOrder = index + 1;
							answer.answerItems[index] = findOne;
							answer.answerItems[index].qtype = ele.questionType;
							answer.answerItems[index].required = ele.required;
						} else {
							answer.answerItems[index] = {
								questionId: ele.id,
								content: null,
								contentArray: [],
								completed: false,
								itemOrder: index + 1,
								qtype: ele.questionType,
								required: ele.required,
							};
						}
						// this.answer = answer;
					}
					// 特殊处理填空题
					if (ele.questionType == '4') {
						let textCopy = ele.title.replace('<p>', '').replace('</p>', '').replace('<br/>', '');
						// console.log(textCopy, 'textCopytextCopy');
						let spanRegex = new RegExp('<span class="gapfilling-span (.*?)">(.*?)<\\/span>', 'g');
						let formItemList = [];
						let gapfillingItems = textCopy.match(spanRegex);
						gapfillingItems.forEach((pre) => {
							textCopy = textCopy.replace(pre, 'input');
						});
						textCopy.split('input').forEach((ped, index) => {
							formItemList.push({
								type: 'text',
								content: ped,
							});
							if (index < textCopy.split('input').length - 1) {
								formItemList.push({
									type: 'input',
									content: '',
									id: index,
								});
							}
						});
						ele.formItemList = formItemList;
					}
					this.form = this.dataList;
					this.answer.id = this.form.id;
				});
				if (this.answer1) {
					this.answer.answerItems = JSON.parse(JSON.stringify(this.answer1.answerItems));
				}
				//已填写，无需初始化答案
				if (!this.isWrite) {
					this.initAnswer();
				}
			},
			// 跳转到签名页面
			goToSign(type) {
				if (this.canClick) return;
				// 设置state以便ca页面取到
				this.$store.commit('global/setState', {
					attr: 'signer',
					data: this[`${type}Signer`],
				});
				// 跳转到签名页面
				this.go('ca');
			},
			initAnswer() {
				let titleItemArray = this.form.titleItems;
				for (let tIndex in titleItemArray) {
					let questionArray = titleItemArray[tIndex].questionItems;
					for (let qIndex in questionArray) {
						let question = questionArray[qIndex];
						this.answer.answerItems.push({
							questionId: question.id,
							content: null,
							contentArray: [],
							completed: false,
							itemOrder: question.itemOrder,
							required: question.required,
							qtype: question.questionType,
						});
					}
				}
			},
			base64ToBlob(base64) {
				let arr = base64.split(',');
				let mime = arr[0].match(/:(.*?);/)[1];
				let bstr = atob(arr[1]);
				let n = bstr.length;
				let u8arr = new Uint8Array(n);
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				return new Blob([u8arr], { type: mime });
			},

			goSub() {
				// 勾选细则必须签名
				if (this.confirmR && !this.qianqiwanhuImgSrc && !this.signPic) {
					this.$toast('请进行签名');
					return;
				}
				console.log(this.answer, 'this.answer');
				// utils.ui.tips('提交成功');
				// 必填校验
				let isAllIn = true;
				for (let i in this.answer.answerItems) {
					if (this.answer.answerItems[i].required == '1') {
						if (
							this.answer.answerItems[i].qtype == '2' ||
							this.answer.answerItems[i].qtype == '4'
						) {
							if (this.answer.answerItems[i].contentArray.length == 0) {
								isAllIn = false;
							} else {
								const isValue = this.answer.answerItems[i].contentArray.some((val) => val);
								if (!isValue) {
									isAllIn = false;
								}
							}
						} else {
							if (!this.answer.answerItems[i].content) {
								isAllIn = false;
							}
						}
					}
				}
        // 签名
        if(this.qianqiwanhuImgSrc || this.signPic) {
        } else {
          isAllIn = false;
        }
				this.$toast('正在保存，请勿离开页面...');
				if (isAllIn) {
					// 全部填写走提交接口
					console.log('全部填写走提交接口');
					this.toSub();
				} else {
					// 部分填写走保存接口
					console.log('部分填写走保存接口');
					this.toSave();
				}
				return;
			},
			async toSub() {
				this.loading = true;
				if (this.qianqiwanhuImgSrc) {
					const fileName = utils.creator.uuid() + '.png';
					const file = this.base64ToBlob(this.qianqiwanhuImgSrc);
					const formData = new FormData();
					formData.append('file', file, fileName);
					formData.append('folder', 'qianqiwanhu_sign');
					const res = await cosUpload(formData, true);
					this.signPic = res.data;
				}
				// 保存答案
				answerSubmit(this.answer)
					.then((re) => {
						console.log(re, 're');
						if (re.code === 200) {
							this.getSave(re.msg, '1');
						} else {
							this.loading = false;
							// utils.ui.confirm(re.message);
						}
					})
					.catch((e) => {});
				this.loading = false;
			},
			async toSave() {
				this.loading = true;
				if (this.qianqiwanhuImgSrc) {
					const fileName = utils.creator.uuid() + '.png';
					const file = this.base64ToBlob(this.qianqiwanhuImgSrc);
					const formData = new FormData();
					formData.append('file', file, fileName);
					formData.append('folder', 'qianqiwanhu_sign');
					const res = await cosUpload(formData, true);
					this.signPic = res.data;
				}
				// 保存答案
				answerSubmit(this.answer)
					.then((re) => {
						console.log(re, 're');
						if (re.code === 200) {
							this.getSave(re.msg, '0');
						} else {
							this.loading = false;
							// utils.ui.confirm(re.message);
						}
					})
					.catch((e) => {});
				this.loading = false;
			},
			async getSave(id, qsFillInAll) {
				let params = {
					id: this.getUrlParam('id'),
					answerId: id,
					qsFillInAll: qsFillInAll,
					surveyId: this.surveyId,
					signPic: this.info.signPic ? this.info.signPic : this.signPic,
          // mpStatus: '进行中'
				};
				const res = await updateVisitDetail(params);
				console.log(res, 'res111111');
				if (res.code == 200) {
					this.loading = false;
					if (qsFillInAll == '0') {
						Dialog.confirm({
							title: '温馨提示',
							message: '保存成功，本次问卷有未及时填写的信息',
							confirmButtonText: '返回',
						})
							.then(() => {
								// on confirm
								wx.miniProgram.navigateBack({
									delta: 1,
								});
							})
							.catch(() => {
								// on cancel
							});
						// this.getDetails(1);
					} else {
						Dialog.alert({
							title: '',
							message: '本次问卷保存成功',
						}).then(() => {
							wx.miniProgram.navigateBack({
								delta: 1,
							});
						});
					}
				}
			},
			getUrlParam(name) {
				const queryStr = String(window.location).split('?')[1] || '';
				name = encodeURIComponent(name);
				let arr = new RegExp('(^|&)' + name + '=([^&]*)(&|$)').exec(queryStr);
				if (arr) {
					return decodeURIComponent(RegExp.$2);
				} else {
					return '';
				}
			},
		},
	};
</script>

<style lang="scss" scoped>
	@import '@/assets/css/demo/index.scss';
	.apply-form {
		height: 100%;
		position: relative;
		// background-color: #f6f6f6;
	}
	.questiion_head {
		width: 100%;
		background-color: #e3eeff;
		position: relative;
		background-image: url('~img/cydnQt/bg.png');
		background-repeat: repeat-x;
		background-size: 100% auto;
		height: 260px;
		padding: 12px;
		.head_title {
			img {
				width: 130px;
			}
		}
		.head_sub_tip {
			font-size: 13px;
			margin-top: 6px;
		}
		.bg_box {
			background-image: url('~img/cydnQt/bg_small.png');
			width: 100%;
			height: 83px;
			background-repeat: repeat-x;
			background-size: 100% 100%;
			margin-top: 30px;
			display: flex;
			align-content: center;

			.flex {
				display: flex;
				align-items: center;
				margin-left: 20px;
				margin-right: 10px;
				// padding-left: 20px;
				// padding-top: 15px;
				.short {
					width: 40px;
					height: 40px;
					border-radius: 5px;
					background-color: #3282e4;
					font-size: 15px !important;
					font-family: Source Han Sans SC;
					color: #ffffff;
					text-align: center;
					display: -webkit-box;
					display: -ms-flexbox;
					display: flex;
					-webkit-box-pack: center;
					-ms-flex-pack: center;
					justify-content: center;
					-webkit-box-align: center;
					-ms-flex-align: center;
					align-items: center;
					line-height: 18px;
				}
				.content {
					margin-left: 8px;
					.name {
						color: #000;
					}
					.code {
						color: #5f6269;
						font-size: 12px;
					}
				}
			}
		}
	}
	.content_box {
		position: absolute;
		top: 192px;
		padding-bottom: 300px;
		overflow-y: auto;
		height: calc(100vh - 192px);
		background-color: #f6f6f6;
	}
	.question {
		width: 100vw;
		//   height: 100vh;
		//   background-color: #f6f6f6;
		// position: relative;
		// background-image: url("https://zx-1311146360.cos.ap-shanghai.myqcloud.com/wx_h5/wx_h5_top.png");
		// background-repeat: repeat-x;
		// background-size: 100% auto;
		padding: 13px;
		.title-qt {
			font-family: Alibaba PuHuiTi;
			font-weight: 600;
			font-size: 17px;
			color: #356ded;
			margin-bottom: 10px;
		}
	}
	.question-body-btn {
		margin: 40px;
		height: 79px;
		background: #4b91e7;
		border-radius: 3px;
		font-size: 16px;
		font-family: Alibaba PuHuiTi;
		font-weight: 400;
		color: #ffffff;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.question-title {
		height: 89px;
		// border: 1px solid red;
		.apply-top-title1 {
			margin: 40px 0 0 28px;
			font-size: 21px;
			font-family: Source Han Sans SC;
			font-weight: 500;
			color: #ffffff;
		}
		.apply-top-title2 {
			margin: 6px 0 0 28px;
			font-size: 17px;
			font-family: Source Han Sans SC;
			font-weight: 500;
			color: #ffffff;
		}
	}

	/* 问卷内容 */
	.question-item {
		background: #ffffff;
		box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.06);
		border-radius: 9px;
		padding: 18px;
		margin-bottom: 16px;
		/* flex-wrap: wrap; */
	}
	.question-item-title {
		/* height: 50px; */
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		font-size: 15px;
		font-weight: 400;
		/* line-height: 59px; */
		color: #2c2c2c;
	}
	.question-ans {
		font-size: 14px;
		font-weight: 400;
		color: #777777 !important;
		/* display: flex;
      flex-direction: column;
      justify-content: space-between; */
		margin-top: 14px;
		display: flex;
		align-items: center !important;
		/* border: 1px solid red; */
		/deep/.van-radio__label {
			color: #777777 !important;
		}
	}

	/deep/.van-checkbox__label {
		color: #777777 !important;
	}
	.question-num {
		width: 68px;
		height: 24px;
		background: #ffffff;
		border: 1px solid #e0e1e5 !important;
		border-radius: 2px;
		margin: 0 8px;
		font-size: 13px;
		font-weight: 400;
		padding: 0 8px;
	}
	.question-item-title1 {
		font-size: 15px;
		font-weight: 400;
		color: #2c2c2c;
		/* display: flex;
      align-items: center; */
		/* flex-wrap: wrap; */
	}
	.question-num1 {
		width: 50px;
		height: 20px;
		background: #ffffff;
		border: 1px solid #e0e1e5 !important;
		border-radius: 2px;
		margin: 0 8px;
		margin-top: 6px;
		font-size: 13px;
		font-weight: 400;
		color: #777777;
		padding: 0 8px;
		display: inline-table;
	}
	.question-item-title2 {
		margin-top: 10px;
		font-size: 12px;
		font-family: Alibaba PuHuiTi;
		font-weight: 400;
		color: #777777;
	}
	.submit-btn {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 60px;
		//   background: #e3eeff;
		border-radius: 3px;
		font-size: 16px;
		font-family: Alibaba PuHuiTi;
		font-weight: 400;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.submit-bo {
		background: #356ded;
		height: 44px;
		width: calc(100% - 40px);
		color: #ffffff;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 20px;
	}
	.submit-bi {
		background: #999;
		height: 44px;
		width: calc(100% - 40px);
		color: #ffffff;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 20px;
	}
	input {
		-webkit-appearance: none;
	}
	textarea {
		margin-top: 10px;
		width: 100%;
		-webkit-appearance: none;
		border: 1px solid rgb(238, 232, 232);
		padding: 2px;
	}
	.tips {
		color: #777;
		margin-top: 5px;
		font-size: 14px;
	}
	.sign-hand {
		border: 1px dashed #777;
		width: 280px;
		height: 120px;
		margin: 30px auto;
		display: flex;
		justify-content: center;
		align-items: center;
	}
</style>
